package testing;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import util.ProgressFeedback;

public class RecursiveParseFiles {
	public static LinkedList<String> fileNames;
	public static ProgressFeedback feedback;
	
	public static void main(String[] args) throws IOException {
		JFileChooser chooser;
		File rootFolderLocation, saveTo;
		int status;

		fileNames = new LinkedList<String>();
		
		chooser = new JFileChooser();
		chooser.setDialogTitle("Where are the tv shows?");
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		status = chooser.showOpenDialog(null);
		if(status == JFileChooser.APPROVE_OPTION){
			rootFolderLocation = chooser.getSelectedFile();
			System.err.println(rootFolderLocation.getCanonicalPath());
			
			feedback = new ProgressFeedback("Scanning",0);
			listFiles(rootFolderLocation);
			
			chooser = new JFileChooser();
			chooser.setDialogTitle("Where do you want to save the list?");
			chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
			status = chooser.showSaveDialog(null);
			if(status == JFileChooser.APPROVE_OPTION){
				saveTo = chooser.getSelectedFile();
				System.err.println(saveTo.getCanonicalPath()+"/"+saveTo.getName());
				
				BufferedWriter writer = new BufferedWriter(new FileWriter(saveTo));
				for(String s:fileNames){
					writer.write(s);
					writer.newLine();
				}
				writer.close();
				JOptionPane.showMessageDialog(null, "Successfully compleated");
			}else{
				JOptionPane.showMessageDialog(null, "Canceled");
			}
		}else{
			JOptionPane.showMessageDialog(null, "Canceled");
		}

		System.exit(0);
	}

	private static void listFiles(File folder) throws IOException {
		String[] folders = folder.list();
		feedback.setMax(feedback.getMaximum()+folders.length);
		for(String s : folders){
			File f = new File(folder.getCanonicalPath()+"/"+s);
			if (f.isDirectory()){
				listFiles(f);
			}else if(f.getName().startsWith(".") == false){
				if (isVideo(f.getName().toLowerCase())){
					fileNames.add(f.getName());
				}
			}
			feedback.setValue(feedback.getValue()+1);
		}
	}

	private static boolean isVideo(String name) {
		if (name.endsWith(".avi")){
			return true;
		}else if (name.endsWith(".mkv")){
			return true;
		}else if (name.endsWith(".mov")){
			return true;
		}
		return false;
	}
}
